package vn.edu.uit.chemistry.utilities;

import java.io.IOException;
import java.net.ServerSocket;
import java.net.Socket;

import android.content.Context;

public class TCPServerReceiver implements Runnable {

	private ServerSocket serverSocket;
	private Thread thread;

	Context ctx;

	public TCPServerReceiver(Context _ctx) {
		this.ctx = _ctx;

	}

	// public static TCPServer getInstance() {
	// if (server == null) {
	// server = new TCPServer();
	// }
	//
	// return server;
	// }

	public boolean start() {
		try {
			serverSocket = new ServerSocket(9999);
			System.out.println("Wating for clients...");
			thread = new Thread(this);
			thread.start();
			while (!thread.isAlive()) {
				//
			}
		} catch (IOException e) {
			e.printStackTrace();
		}
		return true;
	}

	public boolean stop() {
		try {
			serverSocket.close();
		} catch (IOException e) {
			e.printStackTrace();
		}
		return true;
	}

	public void run() {
		while (true) {
			try {
				Socket sk = serverSocket.accept();
				String host = sk.getInetAddress().getHostAddress()
						.toString();
				new ClientThreadReveiver(sk, host, ctx).start();
			} catch (IOException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
		}
	}
}
